<?php

declare(strict_types=1);

namespace app\controllers;

use core\{Validation, Session};
use app\models\Auth;

class Signup extends \core\Controller
{
    // 显示注册表单
    public function index(): void
    {
        $this->pageInfo = ['title' => '登录'];
        $this->view('user/signup');
    }

    // 验证注册
    public function check()
    {
        if (strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') {
            // 检测验证码
            $captcha = $_POST['captcha'];
            if (strtolower($captcha) !== strtolower(session('captcha'))) {
                return json('验证码错误');
            }

            // 表单数据
            $data = [
                'email'    => $_POST['email'],
                'username' => $_POST['username'],
                'password' => $_POST['password'],
            ];
            // 验证规则
            $rules  = [
                'email'    => ['email',    '',      '邮箱格式错误'],
                'username' => ['required', '3,32',  '姓名应为 3-32 个字符'],
                'password' => ['required', '6,250', '密码应为 6 个字符及以上'],
            ];
            // 验证
            $validate = new Validation($data, $rules);
            $result = $validate->check();

            // 验证不通过
            if (!$result) {
                return json($validate->error);
            }

            $auth = new Auth();

            // 用户名已存在
            if ($auth->findByName($data['username'])) {
                return json('用户名已存在');
            }

            // 写入数据
            $user = $auth->save($data);
            if (!$user) {
                return json('用户注册失败');
            }

            // 注册成功，设置 session
            Session::set([
                'user_id'   => $user['id'],
                'user_name' => $user['username'],
            ]);

            json('注册成功', 'success');
            return (url("/user/show/{$user['id']}"));
        }
    }
}
